//
//  DownLoadTool.m
//  lisure0.1
//
//  Created by xalo on 16/4/25.
//  Copyright © 2016年 Mr.wangYongxu. All rights reserved.
//

#import "DownLoadTool.h"


@interface DownLoadTool ()<NSURLSessionDownloadDelegate>

@property(nonatomic, strong)NSURLSession* session;//根据session生成一个task
@property(nonatomic, strong)NSURLSessionTask* task;//下载任务
@property(nonatomic, retain)PlayInfoModel* model;
@property(nonatomic, copy)CompleteDownLoad completeDownLoad;
@property(nonatomic, copy)DownLoading downLoading;

@end

@implementation DownLoadTool

-(instancetype)initWithMoldel:(PlayInfoModel *)model{

    self = [super init];
    if (self) {
        self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];//细颗粒度的调用；
        self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:model.musicUrl]];
        self.model = model;
    }
    return self;
}

//开始下载
-(void)startDownLoad{
    [self.task resume];
}
//暂停下载
-(void)pauseDownLoad{
    [self.task suspend];
}
//取消下载
-(void)cancelDownLoad{
    [self.task cancel];
}

//完成下载
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    if (self.delegate&&[self.delegate respondsToSelector:@selector(downLoadidiFinishedUrl:)]) {
         [self.delegate downLoadidiFinishedUrl:self.model.musicUrl];
    }

    NSString* filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString *urlstr = [filePath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    //文件管理器
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:urlstr error:nil];
    [self.session invalidateAndCancel];
    self.session = nil;
    if (self.completeDownLoad) {
        self.completeDownLoad(filePath,self.model);
    }
    [[DataManager defauleDataManager] InsertDataWithModel:self.model withFilePath:filePath];
    [[DownLoadViewController sharedDownLoad].downLoadCompleteArr removeAllObjects];
    [[DownLoadViewController sharedDownLoad].downLoadCompleteArr addObjectsFromArray:[[DataManager defauleDataManager] DataWithDownLoad]];
}

//正在下载
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    float progress = totalBytesWritten * 100.00/totalBytesExpectedToWrite;//当前进度
//    NSLog(@"%@",[NSThread currentThread]);
    if (self.downLoading) {
        self.downLoading(progress);
    }

}

-(void)didDownLoading:(DownLoading)downLoading complete:(CompleteDownLoad)complete{

    self.downLoading = downLoading;
    self.completeDownLoad = complete;

}

@end
